﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using E5_KhuyenMaiVang.Models;
using E5_KhuyenMaiVang.Email;
using System.Data;
using System.Web.Security;

namespace E5_KhuyenMaiVang.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
        GoldDealEntities db = new GoldDealEntities();

        #region ThongKe

        private void LoadCompanies()
        {
            List<COMPANY> companies = db.COMPANY.ToList();
            ViewBag.Companies = companies;
        }
        private List<DEAL> LoadDeals(int SelectedIndex)
        {
            List<DEAL> deals = new List<DEAL>();
            if (SelectedIndex != 0)
            {
                deals = db.DEAL.Where(d => d.CompanyID == SelectedIndex).ToList();
            }
            else
            {
                deals = db.DEAL.ToList();
            }
            ViewBag.SelectedIndex = SelectedIndex;
            return deals;
        }
        [HttpPost]
        public ActionResult SearchTKDT_DoanhNghiep(int CompanyID)
        {
            LoadCompanies();
            List<DEAL> deals = LoadDeals(CompanyID);
            return View("TKDT_DoanhNghiep", deals);
        }
        public ActionResult TKDT_DoanhNghiep()
        {
            LoadCompanies();
            List<DEAL> deals = LoadDeals(0);
            return View(deals);
        }
        //END TKDT_DoanhNghiep

        private List<DEAL> LoadDeals(int Month, int Year)
        {
            List<DEAL> deals = db.DEAL.ToList();
            int nDeal = deals.Count;
            List<int> SoldQuantities = new List<int>(nDeal);
            List<VOUCHER> vouchers = db.VOUCHER.ToList();
            for (int i = 0; i < nDeal; i++)
            {
                DEAL deal = deals[i];
                int SoldQuantity = 0;
                foreach (var item in vouchers)
                {
                    DateTime date = item.PurchaseDate;
                    if ((date.Month == Month && date.Year == Year) || (Month == 0 && Year == 0) || (Month == 0 && date.Year == Year) || (date.Month == Month && Year == 0))
                    {
                        if (item.DealID == deal.DealID)
                        {
                            SoldQuantity++;
                        }
                    }
                }
                SoldQuantities.Add(SoldQuantity);
            }
            ViewBag.SoldQuantities = SoldQuantities;
            ViewBag.SelectedMont = Month;
            ViewBag.SelectedYear = Year;
            return deals;
        }

        public ActionResult TKDT_Thang()
        {
            List<DEAL> deals = LoadDeals(0, 0);
            return View(deals);
        }
        [HttpPost]
        public ActionResult SearchTKDT_Thang(int Month = 0, int Year = 0)
        {
            List<DEAL> deals = LoadDeals(Month, Year);
            return View("TKDT_Thang", deals);
        }
        //END TKDT_Thang

        private void LoadCategories()
        {
            List<CATEGORY> Categories = db.CATEGORY.ToList();
            ViewBag.Categories = Categories;
        }
        private List<DEAL> LoadDealsbyCategory(int CategoryID)
        {
            List<DEAL> deals = new List<DEAL>();
            if (CategoryID != 0)
            {
                deals = db.DEAL.Where(d => d.CategoryID == CategoryID).ToList();
            }
            else
            {
                deals = db.DEAL.ToList();
            }
            ViewBag.CategoryID = CategoryID;
            return deals;
        }
        public ActionResult TKDT_KhuyenMai()
        {
            LoadCategories();
            List<DEAL> deals = LoadDealsbyCategory(0);
            return View(deals);
        }
        [HttpPost]
        public ActionResult SearchTKDT_KhuyenMai(int CategoryID = 0)
        {
            LoadCategories();
            List<DEAL> deals = LoadDealsbyCategory(CategoryID);
            return View("TKDT_KhuyenMai", deals);
        }

        #endregion

        #region TinKhuyenMai

        private List<DEAL> getAllDeals()
        {
            ViewBag.DealStatuses = db.DEAL_STATUS;
            return db.DEAL.ToList();
        }

        [HttpPost]
        public ActionResult SearchDeal(int Status = 0, string DealName = "")
        {
            List<DEAL> deals = new List<DEAL>();
            if (Status != 0)
                deals = getAllDeals().Where(p => p.DealName.Contains(DealName) && p.StatusID == Status).ToList();
            else
                deals = getAllDeals().Where(p => p.DealName.Contains(DealName)).ToList();
            return View("TKM_QuanLy", deals);             
        }

        [HttpPost]
        public ActionResult UpdateDealStatus(int Status = 0, int DealID = 0)
        {
            if (Status != 0 && DealID != 0)
            {
                DEAL updateDeal = db.DEAL.First(d => d.DealID == DealID);
                updateDeal.StatusID = Status;
                db.SaveChanges();
                if (Status == 2)
                {
                    List<EMAIL> emails = db.EMAIL.Where(e => e.CityID == updateDeal.CityID).ToList();
                    foreach (var item in emails)
                    {
                        try
                        {
                            string link ="#";
                            string content = @"<h2>Chào bạn !</h2><h3>Chúng tôi vừa ra mắt khuyến mãi '"+updateDeal.DealName+"'</h3><h4>"+updateDeal.Description+"</h4><a href="+'"' + link + '"'+">"+" <img src="+'"'+updateDeal.Image+'"'+"/>"+"</a>";
                            bool rs = EmailService.SendMail("E5Group", "e5webgroup@gmail.com", "hcmusfit", item.Email1, "Khuyến mãi mới hấp dẫn", content);
                        }
                        catch { }
                    }
                }
            }
            return View("TKM_QuanLy", getAllDeals());
        }

        public ActionResult TKM_QuanLy()
        {
            return View(getAllDeals());
        }

        public ActionResult TKM_Them()
        {
            ViewBag.CompanyID = new SelectList(db.COMPANY, "CompanyID", "CompanyName");
            ViewBag.StatusID = new SelectList(db.DEAL_STATUS, "StatusID", "StatusName");            
            ViewBag.CategoryID = new SelectList(db.CATEGORY, "CategoryID", "CategoryName");
            ViewBag.CityID = new SelectList(db.CITY, "CityID", "CityName");           
            return View();
        }

        [HttpPost]
        public ActionResult TKM_Them(DEAL deal)
        {            
            try
            {
                if (ModelState.IsValid)
                {
                    db.DEAL.AddObject(deal);
                    db.SaveChanges();
                    return RedirectToAction("TKM_Quanly");
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);                
            }
            ViewBag.CompanyID = new SelectList(db.COMPANY, "CompanyID", "CompanyName");
            ViewBag.StatusID = new SelectList(db.DEAL_STATUS, "StatusID", "StatusName");
            ViewBag.CategoryID = new SelectList(db.CATEGORY, "CategoryID", "CategoryName");
            ViewBag.CityID = new SelectList(db.CITY, "CityID", "CityName");
            return View(deal);
        }

        private DEAL getDeal(int dealID)
        {
            return db.DEAL.First(p => p.DealID == dealID);
        }

        public ActionResult TKM_CapNhat(int dealID)
        {
            ViewBag.CompanyID = new SelectList(db.COMPANY, "CompanyID", "CompanyName", getDeal(dealID).CompanyID);
            ViewBag.StatusID = new SelectList(db.DEAL_STATUS, "StatusID", "StatusName", getDeal(dealID).StatusID);
            ViewBag.CategoryID = new SelectList(db.CATEGORY, "CategoryID", "CategoryName", getDeal(dealID).CategoryID);
            ViewBag.CityID = new SelectList(db.CITY, "CityID", "CityName", getDeal(dealID).CityID);
            return View(getDeal(dealID));
        }

        [HttpPost]
        public ActionResult TKM_CapNhat(DEAL deal)
        {
            if (ModelState.IsValid)
            {
                db.DEAL.Attach(deal);
                db.ObjectStateManager.ChangeObjectState(deal, EntityState.Modified);
                //DEAL d = getDeal(deal.DealID);
                //d = deal;
                db.SaveChanges();
                return RedirectToAction("TKM_Quanly");
            }
            ViewBag.CompanyID = new SelectList(db.COMPANY, "CompanyID", "CompanyName", getDeal(deal.DealID).CompanyID);
            ViewBag.StatusID = new SelectList(db.DEAL_STATUS, "StatusID", "StatusName", getDeal(deal.DealID).StatusID);
            ViewBag.CategoryID = new SelectList(db.CATEGORY, "CategoryID", "CategoryName", getDeal(deal.DealID).CategoryID);
            ViewBag.CityID = new SelectList(db.CITY, "CityID", "CityName", getDeal(deal.DealID).CityID);
            return View(deal);
        }

        public ActionResult TKM_Xoa(int dealID)
        {
            DEAL  deal= db.DEAL.Single(p => p.DealID == dealID);
            try
            {
                db.DEAL.DeleteObject(deal);
                db.SaveChanges();
                ViewBag.Success = "Deal '" + deal.DealName + "' is deleted.";
            }
            catch {
                ViewBag.Error = "Cannot delete deal '"+deal.DealName+"' ,please check relation to voucher table.";
            }            
            return View("TKM_Quanly",getAllDeals());
        }

        #endregion

        #region DonDatHang

        private List<VOUCHER> getAllVouchers()
        {           
            ViewBag.VoucherStatuses = db.VOUCHER_STATUS;            
            return db.VOUCHER.ToList();
        }

        [HttpPost]
        public ActionResult SearchVoucher(int Status = 0, string DealName = "")
        {
            List<VOUCHER> vouchers = new List<VOUCHER>();
            if (Status != 0)
                vouchers = getAllVouchers().Where(p => p.DEAL.DealName.Contains(DealName) && p.StatusID == Status).ToList();
            else
                vouchers = getAllVouchers().Where(p => p.DEAL.DealName.Contains(DealName)).ToList();
            return View("DDH_QuanLy", vouchers);
        }

        [HttpPost]
        public ActionResult UpdateVoucherStatus(int Status = 0, int VoucherID = 0)
        {
            if (Status != 0 && VoucherID != 0)
            {
                VOUCHER updateVoucher = db.VOUCHER.First(v => v.VoucherID == VoucherID);
                updateVoucher.StatusID = Status;
                db.SaveChanges();                
            }
            return View("DDH_QuanLy", getAllVouchers());
        }

        public ActionResult DDH_QuanLy()
        {
            return View(getAllVouchers());
        }

        public ActionResult DDH_HoanTien()
        {
            LoadCompanies();
            List<DEAL> deals= LoadDeals(0);
            return View(deals);
        }
        [HttpPost]
        public ActionResult SearchDDH_HoanTien(int CompanyID) {
            LoadCompanies();
            List<DEAL> deals = LoadDeals(CompanyID);
            return View("DDH_HoanTien", deals);
        }
        [HttpPost]
        public ActionResult DongYHoanTien(int DealID) {
            DEAL updateDeal = db.DEAL.First(d => d.DealID == DealID);
            updateDeal.StatusID = 6;//Bi huy
            db.SaveChanges();

            return RedirectToAction("DDH_QuanLy");
        }
        #endregion

        #region DoanhNghiep

        [HttpPost]
        public ActionResult SearchCompany(string CompanyName)
        {
            return View("DN_QuanLy", db.COMPANY.Where(c => c.CompanyName.Contains(CompanyName)).ToList());
        }

        public ActionResult DN_QuanLy()
        {
            return View(db.COMPANY.ToList());
        }

        public ActionResult DN_Them()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DN_Them(CompanyView company)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Insert vào membership
                    MembershipCreateStatus createStatus;
                    MembershipUser user = Membership.CreateUser(company.Username, company.Password, company.Email, null, null, true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        CompanyManager.AddCompany(company, (Guid)user.ProviderUserKey);
                        Roles.AddUsersToRole(new string[] { company.Username }, "Company");
                        return RedirectToAction("DN_QuanLy");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }

                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }

            return View();
        }

        public ActionResult DN_CapNhat(int companyID)
        {
            return View(CompanyManager.ToCompanyView(db.COMPANY.First(c => c.CompanyID == companyID)));
        }

        [HttpPost]
        public ActionResult DN_CapNhat(CompanyView cv)
        {            
            COMPANY c = db.COMPANY.First(a => a.CompanyID == cv.CompanyID);
            CompanyManager.ToCompany(c, cv);
            db.SaveChanges();
            return RedirectToAction("DN_QuanLy");
        }

        public ActionResult DN_Xoa(int companyID)
        {
            try
            {
                COMPANY company = db.COMPANY.First(c => c.CompanyID == companyID);
                db.COMPANY.DeleteObject(company);
                db.SaveChanges();
                ViewBag.Success = "Xóa doanh nghiệp thành công.";
                return View("DN_QuanLy", db.COMPANY.ToList());
            }
            catch {
                ViewBag.Error = "Vui lòng xóa tất cả thông tin liên quan tới doanh nghiệp trước khi xóa doanh nghiệp này.";
                return View("DN_QuanLy", db.COMPANY.ToList());
            }
            
        }        

        public ActionResult AutoCompleteData(string term)
        {
            var model = db.COMPANY.Where(c => c.CompanyName.Contains(term)).Select(c => c.CompanyName);  
            return Json(model.ToArray(), JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region ThanhVien

        private List<MEMBER> LoadMembers(string MemberName)
        {
            List<MEMBER> members = db.MEMBER.Where(m => m.MemberName.Contains(MemberName)).ToList();
            int nMember = members.Count;
            List<int> VouchersBuy = new List<int>(nMember);
            List<int> VouchersPay = new List<int>(nMember);
            List<double> MoneyPay = new List<double>(nMember);
            for (int i = 0; i < nMember; i++)
            {
                int temp = 0;
                double tempd = 0;
                VouchersBuy.Add(temp);
                VouchersPay.Add(temp);
                MoneyPay.Add(tempd);
            }
            List<VOUCHER> vouchers = db.VOUCHER.ToList();
            foreach (var item in vouchers)
            {
                for (int i = 0; i < nMember; i++)
                {
                    if (item.MemberID == members[i].MemberID)
                    {
                        VouchersBuy[i] += 1;
                        if (item.StatusID > 1)
                        {
                            VouchersPay[i] += 1;
                            MoneyPay[i] += item.Price;
                        }
                    }
                }
            }
            ViewBag.VouchersBuy = VouchersBuy;
            ViewBag.VouchersPay = VouchersPay;
            ViewBag.MoneyPay = MoneyPay;
            ViewBag.SearchName = MemberName;
            return members;
        }
        public ActionResult TV_QuanLy()
        {
            List<MEMBER> members = LoadMembers("");
            return View(members);
        }
        [HttpPost]
        public ActionResult SearchTV_QuanLy(string MemberName)
        {
            List<MEMBER> members = LoadMembers(MemberName);
            return View("TV_QuanLy", members);
        }
        public ActionResult DeleteTV_QuanLy(int MemberID)
        {
            db.MEMBER.DeleteObject(db.MEMBER.First(m => m.MemberID == MemberID));
            db.SaveChanges();
            List<MEMBER> members = LoadMembers("");
            return View("TV_QuanLy", members);
        }

        public ActionResult TV_Them()
        {
            return View();
        }

        [HttpPost]
        public ActionResult TV_Them(MemberView member)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Insert vào membership
                    MembershipCreateStatus createStatus;
                    MembershipUser user = Membership.CreateUser(member.Username, member.Password, member.Email, null, null, true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        MemberManager.AddMember(member, (Guid)user.ProviderUserKey);
                        Roles.AddUsersToRole(new string[] { member.Username }, "Member");                        
                        return RedirectToAction("TV_QuanLy");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }

            return View();
        }

        #endregion

        #region BinhLuan

        private void LoadDealBinhLuan()
        {
            ViewBag.Deals = db.DEAL;
        }

        private List<COMMENT> LoadComments(int DealID)
        {
            LoadDealBinhLuan();
            ViewBag.SelectedDeal = DealID;
            List<COMMENT> comments = new List<COMMENT>();
            if (DealID != 0)
            {
                comments = db.COMMENT.Where(c => c.DealID == DealID).ToList();
            }
            else
            {
                comments = db.COMMENT.ToList();
            }
            return comments;
        }
        public ActionResult BinhLuan()
        {
            List<COMMENT> comments = LoadComments(0);
            return View(comments);
        }
        [HttpPost]
        public ActionResult SearchBinhLuan(int DealID)
        {
            List<COMMENT> comments = LoadComments(DealID);
            return View("BinhLuan", comments);
        }
        public ActionResult DeleteBinhLuan(int CommentID)
        {
            db.COMMENT.DeleteObject(db.COMMENT.First(c => c.CommentID == CommentID));
            List<COMMENT> comments = LoadComments(0);

            return View("BinhLuan", comments);
        }
        [HttpPost]
        public ActionResult PostComment(string Name, string Email, string Content, int dealID)
        {
            COMMENT comment = new COMMENT();
            comment.PostName = Name;
            comment.Text = Content;
            comment.DealID = dealID;
            comment.PostDate = System.DateTime.Now;
            db.AddToCOMMENT(comment);
            db.SaveChanges();
            List<COMMENT> comments = LoadComments(dealID);
            return View("BinhLuan", comments);
        } 


        #endregion

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
